<?php

class Membership_model extends CI_Model {

    function validate() {


        $this->mongo_db->where('username', $this->input->post('username'));
        $this->mongo_db->where('password', md5($this->input->post('password')));
        
        $query = $this->mongo_db->get('community');
        if (!empty($query[0])) {
            return true;
        }
    }

    function create_member() {
        
        do {
            $id = rand(100000000, 999999999);
            $user_id = (string)$id;
            $check_id = $this->mongo_db->get_where('community', array('user_id' => $user_id));
        } while (count($check_id) >0);
//        $user = $this->mongo_db->get_where('community', array('username' => $username));
//        if (empty($user[0])) {
//            $error = '60';
//            return $error;
//        }
        $new_member_insert_data = array(
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'email_address' => $this->input->post('email_address'),
            'username' => $this->input->post('username'),
            'password' => md5($this->input->post('password')),
            'user_id' => $user_id,
            'birthday_month' => "",
            'birthday_day' => "",
            'birthday_year' => "",
            'about' => "",
            'sex' => "",
            'city' => "",
            'state' => "",
            'country' => $this->input->post('country'),
            'height' => "",
            'weight' => "",
            'tracer' => "",
            'shoe' => "",
            'spot' => "",
            'website' => "",
            'facebook' => "",
            'twitter' => "",
            'googleplus' => "",
            'flickr' => "",
            'skype' => "",
            'profile_pic' => "",
            'profile_pic_thumb' => "",
            'profile_cover' => "",
            'profile_cover_pos' => "",
            'mood' => "",
            'team' =>"",
            'follow' => array(),
        );
        //$insert = $this->db->insert('community', $new_member_insert_data);
        
        $insert = $this->mongo_db->insert('community', $new_member_insert_data);
        
        $this->uploadProfilePic($insert,$this->input->post('image'),$this->input->post('imagename'));
        
        return $insert;
         
    }
    function getUserInfos($username){
        $user = $this->mongo_db->get_where('community', array('username' => $username));
        return $user;
    }
    function usernameToID($username){
        $user = $this->mongo_db->get_where('community', array('username' => $username));
        return $user[0]["user_id"];
    }
    function uploadProfilePic($id,$image,$filename){
        $this->load->library('s3');
        $this->load->model('get_profile_infos');
        $this->load->model('manage_login');
        $this->load->library('upload');
        $this->load->model('settings');
        
        
        $uploaddir = './uploads/';
 
// The posted data, for reference
        $file = $image;
        $name = $filename;

// Get the mime
        $getMime = explode('.', $name);
        $mime = end($getMime);

// Separate out the data

// Encode it correctly
        $decodedData = base64_decode($file);

// You can use the name given, or create a random name.
// We will create a random name!

        $randomName = substr_replace(sha1(microtime(true)), '', 12) . '.' . $mime;


        if (file_put_contents($uploaddir . $filename, file_get_contents($file))) {
            echo $filename . ":uploaded successfully";
        } else {
            // Show an error message should something go wrong.
            echo "Something went wrong. Check that the file isn't corrupted";
        }
        
        
        $allowed_types = 'gif|jpg|png|JPG|jpeg';
        $max_size = '100000';
        $max_width = '2624';
        $max_height = '2268';
        
        
        $size = getimagesize($image);
        $type   = exif_imagetype($image);
        $info   = getimagesize($image);
        $mime   = $info['mime']; // mime-type as string for ex. "image/jpeg" etc.
        $width  = $info[0];      // width as integer for ex. 512
        $height = $info[1];      // height as integer for ex. 384
        
        if (!$image) {
            echo "error";
        }
        else{
        
            $username = $this->get_profile_infos->getUsername_id($id);
            
            $user = $this->membership_model->getUserInfos($username);
            
            $org_picture = $this->s3->putObjectFile( "./uploads/".$filename , "leap_s3", $user[0]['user_id']. "/" . $filename, "public-read");

            $this->_createThumbnail($filename,$width,$height,300,"_big");
            $this->_createThumbnail($filename,$width,$height,50,"_thumb");
            
        
            
            $big_picture = $this->s3->putObjectFile("./uploads/" . str_replace(".", "_big.", $filename), "leap_s3", $user[0]['user_id'] . "/" . str_replace(".", "_big.", $filename), "public-read");
            $thmub_picture = $this->s3->putObjectFile("./uploads/" . str_replace(".", "_thumb.", $filename), "leap_s3", $user[0]['user_id'] . "/" . str_replace(".", "_thumb.", $filename), "public-read");

            $profile_pic = "https://s3.amazonaws.com/leap_s3/" . $user[0]['user_id'] . "/" . str_replace(".", "_big.", $filename);
            $profile_pic_thumb = "https://s3.amazonaws.com/leap_s3/" . $user[0]['user_id'] . "/" . str_replace(".", "_thumb.", $filename);
            $profile_pic_original = "https://s3.amazonaws.com/leap_s3/" . $user[0]['user_id'] . "/" . $filename;

            $this->manage_login->updateData("profile_pic",$profile_pic,$user[0]['user_id']);
            $this->manage_login->updateData("profile_pic_thumb",$profile_pic_thumb,$user[0]['user_id']);
            $this->settings->SureRemoveDir('./uploads', false);
        }
    }
    
    function _createThumbnail($fileName,$_width,$_height,$width,$marker) {

        $img_type = '';
        if ($_width > $_height) {
            $img_type = 'wide';
            $config['height'] = $width;
            $config['width'] = round(($_width/$_height)*$width);
        } else if ($_width < $_height) {
            $img_type = 'landscape';
            $config['width'] = $width;
            $config['height'] = round(($_height/$_width)*$width);
        } else {
            $img_type = 'square';
            $config['width'] = $width;
            $config['height'] = $width;
        }
    
        $config['image_library'] = 'gd2';
        $config['allowed_types'] = 'gif|jpg|png|jpeg|JPEG|JPG';
        $config['source_image'] =   './uploads/' .$fileName ;
        $config['new_image'] =   './uploads/' .$fileName;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['thumb_marker'] = $marker;
        
        
        $this->image_lib->clear();
       $this->image_lib->initialize($config);
        
        if (!$this->image_lib->resize()){
            echo $this->image_lib->display_errors();
        }else{
            echo "created";
            echo  './uploads/' . $fileName;
        }
        $fileName_c = str_replace('.',$marker.'.', $fileName);
        //crop
        $conf_new = array(
            'image_library' => 'gd2',
            'source_image' => './uploads/'.$fileName ,
            'maintain_ratio' => FALSE,
            'create_thumb' => FALSE,
            'width' => $width,
            'height' => $width
        );

        if ($img_type == 'wide') {
            $conf_new['x_axis'] = ($config['width'] - $width) / 2;
            $conf_new['y_axis'] = 0;
        } else if ($img_type == 'landscape') {
            $conf_new['x_axis'] = 0;
            $conf_new['y_axis'] = ($config['height'] - $width) / 2;
        } else {
            $conf_new['x_axis'] = 0;
            $conf_new['y_axis'] = 0;
        }
        $this->image_lib->clear();
        
        $this->image_lib->initialize($conf_new);

        if ( ! $this->image_lib->crop())
        {
            echo $this->image_lib->display_errors();
        }
        
    }
}